package com.hc.model.code03.test1.cglib_proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.InvocationHandler;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @version v1.0
 * @ClassName: ProxyFactory
 * @Description: 代理对象工厂，用来获取代理对象
 * @Author: HC
 */
public class ProxyFactory {

    public TrainStation getProxyObject() {
        // 创建增强类
        Enhancer enhancer = new Enhancer();
        // 设置类的字节码
        enhancer.setSuperclass(TrainStation.class);
        // 设置回调对象
        enhancer.setCallback(methodInterceptor());

        return (TrainStation) enhancer.create();
    }

    public MethodInterceptor methodInterceptor() {
        return new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                TrainStation trainStation = TrainStation.class.getDeclaredConstructor().newInstance();
                System.out.println("代理点收取一些费用（cglib代理实现）");
                Object obj = methodProxy.invoke(trainStation, objects);
                return obj;
            }
        };
    }


}
